package org.lzy.shop.fragment

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.lzy.shop.Constant
import org.lzy.shop.activity.CouponListActivity
import org.lzy.shop.activity.CustomMsgListActivity
import org.lzy.shop.activity.LoginActivity
import org.lzy.shop.activity.PersonInfoActivity
import org.lzy.shop.activity.SettingActivity
import org.lzy.shop.address.AddressListActivity
import org.lzy.shop.base.BaseMvvmFragment
import org.lzy.shop.databinding.FragMineBinding
import org.lzy.shop.feedback.FeedBackListActivity
import org.lzy.shop.network.KtorApiService
import org.lzy.shop.network.RefreshTokenRequest
import org.lzy.shop.order.MyOrderActivity
import org.lzy.shop.util.DataStoreUtils
import org.lzy.shop.util.setUrlRound
import org.lzy.shop.viewmodel.MineModel

/**
 * 我的fragment
 */

class MineFragment : BaseMvvmFragment<FragMineBinding, MineModel>(FragMineBinding::inflate) {

    private var isUserInfoLoaded = false
    // 添加一个标志位防止重复刷新Token
    private var isRefreshing = false


    override fun initView() {}

    override fun requestData() {
        if (isTokenValid()) {
            getMyInfo()
            getUserCount()
        } else {
            // 检查是否有refreshToken，如果有则尝试刷新
            val refreshToken = DataStoreUtils.getToken(Constant.REFRESHTOKEN)
            if (!TextUtils.isEmpty(refreshToken) && !isRefreshing) {
                tryRefreshToken()
            } else {
                // 显示登录提示
                binding.pleaseLogintxt.visibility = View.VISIBLE
            }
        }
    }

    override fun onResume() {
        super.onResume()
        // 每次Fragment可见时都检查token状态并刷新数据
        requestData()
    }

    fun getMyInfo(){
        mViewModel.getMyInfo()
    }

    // 刷新token后重新请求用户数据
    private fun requestDataAfterTokenRefresh() {
        if (isTokenValid()) {
            getMyInfo()
            getUserCount()
        } else {
            startActivity(LoginActivity::class.java)
        }
    }

    fun getUserCount(){
        mViewModel.getUserCount()

    }

    // 添加本地方法检查Token是否有效
    private fun isTokenValid(): Boolean {
        // 在Ktor实现中，我们只需要检查Token是否存在即可
        // 因为KtorClient已经实现了自动刷新Token的逻辑
        val token = DataStoreUtils.getToken(Constant.TOKEN)
        return !TextUtils.isEmpty(token)
    }

    private fun tryRefreshToken() {
        val refreshToken = DataStoreUtils.getToken(Constant.REFRESHTOKEN)

        if (!TextUtils.isEmpty(refreshToken) && !isRefreshing) {
            isRefreshing = true

            // 使用协程刷新token
            lifecycleScope.launch(Dispatchers.IO) {
                try {
                    // 调用刷新token的API，只传递refreshToken参数
                    val response = KtorApiService.refreshToken(RefreshTokenRequest(refreshToken))

                    withContext(Dispatchers.Main) {
                        isRefreshing = false
                        if (response?.token != null) {
                            // 保存新token
                            DataStoreUtils.putToken(Constant.TOKEN, response.token)
                            // 如果有新的refreshToken也保存起来
                            response.refreshToken.let {
                                DataStoreUtils.putToken(Constant.REFRESHTOKEN, it)
                            }
                            // 刷新token成功后重新请求数据
                            requestDataAfterTokenRefresh()
                        } else {
                            // 尝试使用另一个refreshToken方法
                            tryAlternativeRefreshToken()
                        }
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                        isRefreshing = false
                        // 异常时尝试备用刷新方法
                        tryAlternativeRefreshToken()
                    }
                }
            }
        } else if (!isRefreshing) {
            startActivity(LoginActivity::class.java)
        }
    }

    // 备用的刷新token方法，使用不同的API调用方式
    private fun tryAlternativeRefreshToken() {
        val refreshToken = DataStoreUtils.getToken(Constant.REFRESHTOKEN)
        if (!TextUtils.isEmpty(refreshToken) && !isRefreshing) {
            isRefreshing = true

            lifecycleScope.launch(Dispatchers.IO) {
                try {
                    // 使用备用的refreshToken方法
                    val response = KtorApiService.refreshToken(refreshToken)

                    withContext(Dispatchers.Main) {
                        isRefreshing = false
                        // 保存新token
                        DataStoreUtils.putToken(Constant.TOKEN, response.data.token)
                        DataStoreUtils.putToken(Constant.REFRESHTOKEN, response.data.refreshToken)
                        // 刷新成功后重新请求数据
                        requestDataAfterTokenRefresh()
                    }
                } catch (e: Exception) {
                    withContext(Dispatchers.Main) {
                        isRefreshing = false
                        // 刷新彻底失败，跳转到登录页
                        startActivity(LoginActivity::class.java)
                    }
                }
            }
        }
    }

    override fun initData() {
        //我的个人信息回调
        mViewModel.myData.observeWithLifecycle(viewLifecycleOwner){myInfoResponse ->
            myInfoResponse?.let {
                binding.frgMineTvUsername.text = myInfoResponse.nickName
                binding.frgMineTvUserMobile.text = myInfoResponse.phone
                binding.pleaseLogintxt.visibility= View.GONE
                DataStoreUtils.putString(Constant.USERID,myInfoResponse.id)
                DataStoreUtils.putString(Constant.MOBILE,myInfoResponse.phone)
                setUrlRound(myInfoResponse.avatarUrl,80f,binding.frgMineIvIcon)
                // 标记用户信息已加载
                isUserInfoLoaded = true
            }
        }
        //用户订单数量回调
        mViewModel.userCountData.observeWithLifecycle(viewLifecycleOwner){userCountResponse ->
            userCountResponse?.let {
                //待付款的数量
                if (userCountResponse.待付款 > 0) {
                    binding.payNum.visibility= View.VISIBLE
                    binding.payNum.text=userCountResponse.待付款.toString()
                }else{
                    binding.payNum.visibility= View.GONE
                }

                //待发货的数量
                if (userCountResponse.待发货 > 0) {
                    binding.pendshipNum.visibility= View.VISIBLE
                    binding.pendshipNum.text=userCountResponse.待发货.toString()
                }else{
                    binding.pendshipNum.visibility= View.GONE
                }

                //待付款的数量
                if (userCountResponse.待收货 > 0) {
                    binding.deliverNum.visibility= View.VISIBLE
                    binding.deliverNum.text=userCountResponse.待收货.toString()
                }else{
                    binding.deliverNum.visibility= View.GONE
                }
                //待评价
                if (userCountResponse.待评价 > 0) {
                    binding.commentNum.visibility= View.VISIBLE
                    binding.commentNum.text=userCountResponse.待评价.toString()
                }else{
                    binding.commentNum.visibility= View.GONE
                }


                //退货/售后
                if (userCountResponse.退款中 > 0) {
                    binding.refundNum.visibility= View.VISIBLE
                    val result = userCountResponse.退款中 + userCountResponse.已退款
                    binding.refundNum.text=result.toString()
                }else{
                    binding.refundNum.visibility= View.GONE
                }

            }

        }

        // 监听ViewModel中的错误信息，用于检测Token相关错误
        mViewModel.errorMessage.observeWithLifecycle(viewLifecycleOwner) {
            it?.let {errorMsg ->
                // 检查是否是认证错误且没有正在刷新token
                if ((errorMsg.contains("401") || errorMsg.contains("未授权") || errorMsg.contains("token无效")) && isTokenValid() && !isRefreshing) {
                    tryRefreshToken()
                }
            }
        }
    }

    // 提取统一的导航方法，处理Token验证和页面跳转
    private fun navigateWithTokenCheck(targetClass: Class<*>, bundle: Bundle? = null) {
        if (isTokenValid()) {
            // 修复：根据bundle是否为null选择不同的startActivity调用
            if (bundle != null) {
                startActivity(targetClass, bundle)
            } else {
                startActivity(targetClass)
            }
        } else {
            startActivity(LoginActivity::class.java)
        }
    }


    override fun allClick() {
        //全部订单
        binding.myOrderLayout.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(Constant.ORDER_POSITION, 0)
            navigateWithTokenCheck(MyOrderActivity::class.java, bundle)
        }

        //设置
        binding.frgMineLlSetting.setOnClickListener {
            navigateWithTokenCheck(SettingActivity::class.java)
        }

        //收货人
        binding.frgMineLlDeliver.setOnClickListener {
            navigateWithTokenCheck(AddressListActivity::class.java)
        }

        //个人信息
        binding.frgMineLlUserinfo.setOnClickListener {
            navigateWithTokenCheck(PersonInfoActivity::class.java)
        }

        //待付款
        binding.waitPayLayout.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(Constant.ORDER_POSITION, 1)
            navigateWithTokenCheck(MyOrderActivity::class.java, bundle)
        }

        //待发货
        binding.pendshipLayout.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(Constant.ORDER_POSITION, 2)
            navigateWithTokenCheck(MyOrderActivity::class.java, bundle)
        }

        //待收货
        binding.deliverLayout.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(Constant.ORDER_POSITION, 3)
            navigateWithTokenCheck(MyOrderActivity::class.java, bundle)
        }

        //待评价
        binding.commentLayout.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(Constant.ORDER_POSITION, 5)
            navigateWithTokenCheck(MyOrderActivity::class.java, bundle)
        }

        //退货
        binding.refundLayout.setOnClickListener {
            val bundle = Bundle()
            bundle.putInt(Constant.ORDER_POSITION, 4)
            navigateWithTokenCheck(MyOrderActivity::class.java, bundle)
        }

        //优惠劵
        binding.frgMineLlMyCoupon.setOnClickListener {
            navigateWithTokenCheck(CouponListActivity::class.java)
        }

        //在线客服
        binding.frgMineLlMyCustomer.setOnClickListener {
            navigateWithTokenCheck(CustomMsgListActivity::class.java)
        }

        //反馈
        binding.frgMineLlMyFeedback.setOnClickListener {
            navigateWithTokenCheck(FeedBackListActivity::class.java)
        }
    }
}